//
//  CountryCode.m
//  EPTool
//
//  Created by guoshiqing on 2018/5/2.
//  Copyright © 2017年 云数动能. All rights reserved.
//

#import "CountryCode.h"
#import "CountryModel.h"

@implementation CountryCode

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        //------------ 另一种获取国家地区码的方法 ------
        // 读取文件
        NSMutableDictionary *dicCode = [self readData];
        // 获取国家名
        NSMutableDictionary *dicCountry = [self getCountryName:dicCode];
        // 归类
        NSMutableDictionary *dicClass = [self classification:dicCountry];
        // 排序
        NSMutableDictionary *dicSort = [self dictionarySort:dicClass];
        
        self.dicCountryCodes = dicSort;
    }
    return self;
}


// ------------------------------------- //
// 读取文件
- (NSMutableDictionary *)readData
{
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"diallingcode" ofType:@"json"];
//    NSData *data = [NSData dataWithContentsOfFile:path];
//    NSError *error = nil;
//    
//    NSArray *arrayCode = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
//    if (error) {
//        return nil;
//    }
    
    NSArray *arrayCode = [NSArray arrayWithObjects:@{@"code":@"HK", @"dial_code":@"+852"},
                                                @{@"code":@"CN", @"dial_code":@"+86"},
                                                 @{@"code":@"MO", @"dial_code":@"+853"},nil];
    
    NSMutableDictionary *dicCode = [NSMutableDictionary dictionary];
    for (NSDictionary *item in arrayCode)
    {
        CountryModel *c = [CountryModel new];
        c.code      = item[@"code"];
        c.dial_code = item[@"dial_code"];
        [dicCode setObject:c forKey:c.code];
    }
    return dicCode;
}

// 获取国家
- (NSMutableDictionary *)getCountryName:(NSMutableDictionary *)dicCode
{
    NSLocale *locale = [NSLocale currentLocale];
    NSArray *countryArray = [NSLocale ISOCountryCodes];
    
    NSMutableDictionary *dicCountry = [NSMutableDictionary dictionary];
    for (NSString *phoneZone in countryArray) {
        if (dicCode[phoneZone])
        {
            CountryModel *c = dicCode[phoneZone];
            
            c.name = [locale displayNameForKey:NSLocaleCountryCode value:phoneZone];
            if ( [c.name isEqualToString:@"台湾"] )
            {
                c.name = @"中国台湾";
            }
            
            c.latin = [self latinize:c.name];
            
            [dicCountry setObject:c forKey:c.code];
        }
        else
        {
            // error...
        }
    }
    return dicCountry;
}

// 归类
- (NSMutableDictionary *)classification:(NSMutableDictionary *)dicCountry
{
    NSMutableDictionary *dicClass = [NSMutableDictionary dictionary];
    for (CountryModel *c in dicCountry.allValues )
    {
        NSString *indexKey = @"";
        if (c.latin.length > 0)
        {
            indexKey = [[c.latin substringToIndex:1] uppercaseString];
            
            char c = [indexKey characterAtIndex:0];
            
            if ( ( c < 'A') || ( c > 'Z' ) )
            {
                continue;
            }
        }
        else
        {
            continue;
        }
        
        NSMutableArray *array = dicClass[indexKey];
        if (!array)
        {
            array = [NSMutableArray array];
            dicClass[indexKey] = array;
        }
        
        [array addObject:c];
    }
    return dicClass;
}

// 排序
- (NSMutableDictionary *)dictionarySort:(NSMutableDictionary *)dicClass
{
    // 内部排序
    for (NSString *key in dicClass.allKeys)
    {
        NSArray *array = dicClass[key];
        // 内部排序
        array = [array sortedArrayUsingComparator:^NSComparisonResult(CountryModel *obj1, CountryModel *obj2) {
            return [obj1.name localizedStandardCompare:obj2.name];
        }];
        dicClass[key] = array;
    }
    
    return dicClass;
}

#pragma mark - 转换标识符(中文国家名转成英文国家名)
- (NSString*)latinize:(NSString*)str
{
    NSMutableString *source = [str mutableCopy];
    CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformToLatin, NO);
    CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformStripDiacritics, NO);
    return source;
}


- (NSString *)getCountryNameWithCode:(NSString *)code
{
    // 入参处理
    NSString *strCode = [code stringByReplacingOccurrencesOfString:@" " withString:@""];
    strCode  = [strCode stringByReplacingOccurrencesOfString:@"+" withString:@""];
    
    // 循环匹配
    NSString *strTmp = @"";
    NSArray *listCountry = nil;
    for (NSString *key in self.dicCountryCodes.allKeys) {
        
        listCountry = self.dicCountryCodes[key];
        for (CountryModel *model in listCountry) {
            strTmp  = [model.dial_code stringByReplacingOccurrencesOfString:@" " withString:@""];
            strTmp  = [strTmp stringByReplacingOccurrencesOfString:@"+" withString:@""];
            if ([strTmp isEqualToString:strCode]) {
                return [NSString stringWithFormat:@"%@", model.name];
            }
        }
    }
    return nil;
}


@end
